#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <cstdio>
#include <cstring>
#include <functional>

namespace ThreadModule
{
    static uint32_t num =  1;
    class Thread
    {
        using func_t = std::function<void()>;
    private:
        void EnableDetach()
        {
            std::cout << "thread detach" << std::endl;
            _isdetach = true;
            return ;
        }

        void EnableRunning()
        {
            _isrunning = true;
        }

        static void* Routine(void* args)
        {
            Thread* self = static_cast<Thread*> (args);
            self->EnableRunning();
            if(self->_isdetach) self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }
        
        
    public:
        Thread(func_t func)
            :_tid(0),
            _isdetach(false),
            _isrunning(false),
            res(nullptr),
            _func(func)
        {
            _name = "thread-" + std::to_string(num++);
        }

        void Detach()
        {
            if(_isdetach) return ;
            _isdetach = true;
            pthread_detach(_tid);
        }

        bool Start()
        {
            if(_isrunning) return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                std::cerr << "create thread error: " << strerror(n) << std::endl;
                return false;
            }

            std::cout << _name << " create success" << std::endl;
            return true;
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    std::cerr << "create thread error: " << strerror(n) << std::endl;
                    return false;
                }
                _isrunning = false;
                std::cout << _name << " stop" << std::endl;
                return true;
            }
            return false;
        }

        void Join()
        {
            if(_isdetach)
            {
                std::cout << _name << " had been detached, could not join" << std::endl;
            }

            int n = pthread_join(_tid, &res);
            if (n != 0)
            {
                std::cerr << "join thread error: " << strerror(n) << std::endl;
                return ;
            }
            std::cout << "join success" << std::endl;
            return ;
        }
        ~Thread()
        {}
        
    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void* res;
        func_t  _func;
    };
}